package org.example.Polls;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;

public class HttpURLConnectionHelper {
	
	private SSLSocketFactory socketFactory;
	
	public HttpURLConnectionHelper (String trustStoreFilename, String trustStorePassword) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
		socketFactory = new CustomTrustStoreSSLSocketFactory(trustStoreFilename, trustStorePassword).createSSLSocketFactory();
	}
	
	/**
	 * Returns either an HttpURLConnection or HttpsURLConnection for the
	 * given serviceUrl.  If the protocol of the serviceUrl is "https",
	 * a custom SSLSocketFactory is set on the connection to allow the 
	 * self-signed certificate to be validated successfully.
	 * @param serviceUrl the url to open a connection to.
	 * @return an instance of HttpURLConnection or HttpsURLConnection.
	 * @throws IOException 
	 */
	public HttpURLConnection openConnection(URL serviceUrl) throws IOException {
		
		if ("https".equals(serviceUrl.getProtocol())) {
			HttpsURLConnection conn = (HttpsURLConnection)serviceUrl.openConnection();
			conn.setSSLSocketFactory(this.socketFactory);
			return conn;
		} else if ("http".equals(serviceUrl.getProtocol())) {
			return (HttpURLConnection)serviceUrl.openConnection();
		} else {
			throw new IllegalArgumentException("Only http or https are supported");
		}
		
	}
	
}
